# views.py
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework import status
from .models import BayInformation
from .serializers import BayInformationSerializer, BayInformationImportSerializer
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage


class AddBayInformationView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = BayInformationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"data": serializer.data, "code": 200})
        else:
            return JsonResponse({"message": serializer.errors, "code": 400}, status=status.HTTP_400_BAD_REQUEST)


class BayInformationListView(APIView):
    def get(self, request, format=None):
        # 获取查询参数
        bay_description = request.query_params.get('bay_description', '')
        first_level_area = request.query_params.get('first_level_area', '')
        second_level_area = request.query_params.get('second_level_area', '')
        page = request.query_params.get('current', 1)
        page_size = request.query_params.get('pageSize', 8)

        # 构造查询条件
        queryset = BayInformation.objects.all()

        if bay_description:
            queryset = queryset.filter(bay_description__icontains=bay_description)
        if first_level_area:
            queryset = queryset.filter(first_level_area__icontains=first_level_area)
        if second_level_area:
            queryset = queryset.filter(second_level_area__icontains=second_level_area)

        # 分页处理
        paginator = Paginator(queryset, page_size)
        try:
            bays = paginator.page(page)
        except PageNotAnInteger:
            bays = paginator.page(1)
        except EmptyPage:
            bays = paginator.page(paginator.num_pages)

        serializer = BayInformationSerializer(bays, many=True)

        return JsonResponse({
            "code": 200,
            "data": {
                "list": serializer.data,
                "total": paginator.count,
                "current": bays.number,
                "pageSize": page_size
            }
        }, status=status.HTTP_200_OK)


class BayInformationDetail(APIView):
    """
    根据 bay_id 获取、更新或删除一个 BayInformation 实例。
    """

    def get_object(self, pk):
        try:
            return BayInformation.objects.get(bay_id=pk)
        except BayInformation.DoesNotExist:
            return None

    def get(self, request, pk, format=None):
        bay = self.get_object(pk)
        if not bay:
            return JsonResponse({"code": 404, "message": "未找到对应记录"}, status=status.HTTP_404_NOT_FOUND)
        serializer = BayInformationSerializer(bay)
        return JsonResponse({"code": 200, "data": serializer.data}, status=status.HTTP_200_OK)

    def put(self, request, pk, format=None):
        bay = self.get_object(pk)
        if not bay:
            return JsonResponse({"code": 404, "message": "未找到对应记录"}, status=status.HTTP_404_NOT_FOUND)

        serializer = BayInformationSerializer(bay, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"code": 200, "message": "修改成功", "data": serializer.data}, status=status.HTTP_200_OK)
        return JsonResponse({"code": 400, "message": "数据校验失败", "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        bay = self.get_object(pk)
        if not bay:
            return JsonResponse({"code": 404, "message": "未找到对应记录"}, status=status.HTTP_404_NOT_FOUND)

        bay.delete()
        return JsonResponse({"code": 200, "message": "删除成功"}, status=status.HTTP_200_OK)

class BatchDeleteBays(APIView):
    def post(self, request, *args, **kwargs):
        entities = request.data.get('entities', [])

        if not isinstance(entities, list) or len(entities) == 0:
            return JsonResponse(
                {"code": 400, "message": "请传入有效的实体列表"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 提取所有 bay_id
        ids_to_delete = [entity.get('bay_id') for entity in entities if 'bay_id' in entity]

        if not ids_to_delete:
            return JsonResponse(
                {"code": 400, "message": "实体列表中没有有效的 bay_id"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 删除符合条件的记录
        deleted_count, _ = BayInformation.objects.filter(bay_id__in=ids_to_delete).delete()

        return JsonResponse(
            {"code": 200, "message": f"成功删除 {deleted_count} 条记录"},
            status=status.HTTP_200_OK
        )

class BatchAddBayInformationView(APIView):
    def post(self, request, *args, **kwargs):
        data_list = request.data.get('list', [])

        if not isinstance(data_list, list) or len(data_list) == 0:
            return JsonResponse({"code": 400, "message": "请传入有效的对象数组"}, status=400)

        # 使用 BayInformationImportSerializer 校验数据
        serializer = BayInformationImportSerializer(data=data_list, many=True)

        if serializer.is_valid():
            # 构造模型实例并批量插入
            BayInformation.objects.bulk_create([
                BayInformation(**item) for item in serializer.validated_data
            ])

            return JsonResponse({
                "code": 200,
                "message": f"成功导入 {len(serializer.validated_data)} 条胎位信息"
            }, status=201)
        else:
            return JsonResponse({
                "code": 400,
                "message": "部分数据校验失败",
                "errors": serializer.errors
            }, status=400)